package com.juice.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.juice.model.Book;
import com.juice.service.IBookService;
import com.juice.utils.Logs;
import com.juice.utils.Pair;
import com.juice.utils.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Comparator;
import java.util.List;
import java.util.Optional;

/**
 * @desc:
 * @author: panxiyi
 * @date: 2023/4/12 7:54 下午
 */

@RestController
@RequestMapping("books")
public class BookController {

    // 创建记录日志对象
    private static final Logger Log = LoggerFactory.getLogger(BookController.class);

    @Autowired
    private IBookService bookService;


    private final static Object lockObj = new Object();

    @GetMapping
    public R getAll() {
        return new R(true, bookService.list());
    }


    @PostMapping
    public R save(@RequestBody Book book) {

        if (book.getId() == null || book.getId().longValue() == 0L) {
            synchronized (lockObj) {
                List<Book> books = bookService.list();
                Optional<Book> first = books.stream().sorted(Comparator.comparing(Book::getId).reversed()).findFirst();
                Long nextId = first.get().getId() + 1;
                book.setId(nextId);
            }
        }
        return new R(bookService.save(book));
    }

    @PutMapping
    public R update(@RequestBody Book book) {
        return new R(bookService.updateById(book));
    }

    @DeleteMapping("{id}")
    public R delete(@PathVariable Integer id) {
        return new R(bookService.delete(id));
    }

    @GetMapping("{id}")
    public R getById(@PathVariable Integer id) {
        return new R(true, bookService.getById(id));
    }

    @GetMapping("{currentPage}/{pageSize}")
    public R getByPage(@PathVariable int currentPage, @PathVariable int pageSize,
                       @RequestParam(name = "type", defaultValue = "") String type,
                       @RequestParam(name = "name", defaultValue = "") String name,
                       @RequestParam(name = "description", defaultValue = "") String description) {

        Logs.common.info(Pair.of("type", type), Pair.of("name", name), Pair.of("description", description));
        IPage<Book> page = bookService.getByPage(currentPage, pageSize, type, name, description);
        if (page.getPages() < currentPage) {
            page = bookService.getByPage((int)page.getPages(), pageSize, type, name, description);
        }
        //
        return new R(true, page);
    }
}
